home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / ohlutil.zip / CP.C < prev    next >
C/C++ Source or Header  |  1990-06-22  |  22KB  |  891 lines

  1. /*  cp.c  -- file copying (main routines)
  2.     Copyright (C) 1989, 1990 Free Software Foundation.
  3.  
  4.     This program is free software; you can redistribute it and/or modify
  5.     it under the terms of the GNU General Public License as published by
  6.     the Free Software Foundation; either version 1, or (at your option)
  7.     any later version.
  8.  
  9.     This program is distributed in the hope that it will be useful,
  10.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.     GNU General Public License for more details.
  13.  
  14.     You should have received a copy of the GNU General Public License
  15.     along with this program; if not, write to the Free Software
  16.     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.     Written by Torbjorn Granlund, and David MacKenzie. */
  19.  
  20. /* Yet to be done:
  21.  
  22.  * Symlink translation. */
  23.  
  24. #include <stdio.h>
  25. #include "cp.h"
  26. #include "getopt.h"
  27. #include "backupfile.h"
  28.  
  29. #ifndef _POSIX_SOURCE
  30. /* This definition assumes that MODE has the S_IFIFO bit set. */
  31. #define mkfifo(path, mode) (mknod ((path), (mode), 0))
  32.  
  33. int geteuid ();
  34. #endif
  35.  
  36. enum backup_type get_version ();
  37.  
  38. #define INITIAL_HASH_MODULE 100
  39.  
  40. #define INITIAL_ENTRY_TAB_SIZE 70
  41.  
  42. /* A pointer to either lstat or stat, depending on
  43.    whether dereferencing of symlinks is done.  */
  44. int (*xstat) ();
  45.  
  46. /* The invocation name of this program.  */
  47. char *program_name;
  48.  
  49. /* If nonzero, dereference symbolic links (copy the files they point to). */
  50. int flag_dereference = 1;
  51.  
  52. /* If nonzero, override protection for target files if possible. */
  53. int flag_force = 0;
  54.  
  55. /* If nonzero, always query before removing existing targets. */
  56. int flag_interactive = 0;
  57.  
  58. /* If nonzero, give the copies the original files' permissions. */
  59. int flag_preserve = 0;
  60.  
  61. /* If nonzero, copy directories recursively and copy special files
  62.    as themselves rather than copying their contents. */
  63. int flag_recursive = 0;
  64.  
  65. /* If nonzero, when copying recursively, skip any subdirectories that are
  66.    on different filesystems from the one we started on. */
  67. int flag_one_file_system = 0;
  68.  
  69. /* If nonzero, display the names of the files before copying them. */
  70. int flag_verbose = 0;
  71.  
  72. /* The error code to return to the system. */
  73. int exit_status = 0;
  74.  
  75. /* If nonzero, effective uid is 0. */
  76. int root;
  77.  
  78. /* The bits to preserve in created files' modes. */
  79. int umask_kill;
  80.  
  81. /* If nonzero, skip unwritable files if not interactive. */
  82. int stdin_not_tty;
  83.  
  84. struct option long_opts[] =
  85. {
  86.   {"backup", 0, NULL, 'b'},
  87.   {"force", 0, &flag_force, 1},
  88.   {"interactive", 0, &flag_interactive, 1},
  89.   {"no-dereference", 0, &flag_dereference, 0},
  90.   {"one-file-system", 0, &flag_one_file_system, 1},
  91.   {"preserve", 0, &flag_preserve, 1},
  92.   {"recursive", 0, &flag_recursive, 1},
  93.   {"suffix", 1, NULL, 'S'},
  94.   {"verbose", 0, &flag_verbose, 1},
  95.   {"version-control", 1, NULL, 'V'},
  96.   {NULL, 0, NULL, 0}
  97. };
  98.  
  99. void
  100. main (argc, argv)
  101.      int argc;
  102.      char *argv[];
  103. {
  104.   int c;
  105.   int ind;
  106.   int make_backups = 0;
  107.   char *version;
  108.  
  109.   program_name = argv[0];
  110.  
  111.   version = getenv ("SIMPLE_BACKUP_SUFFIX");
  112.   if (version)
  113.     simple_backup_suffix = version;
  114.   version = getenv ("VERSION_CONTROL");
  115.  
  116.   /* Find out the current file creation mask, to knock the right bits
  117.      when using chmod.  The creation mask is set to to be liberal, so
  118.      that created directories can be written, even if it would not
  119.      have been allowed with the mask this process was started with.  */
  120.  
  121.   umask_kill = 0777777 ^ umask (0);
  122.  
  123.   while ((c = getopt_long (argc, argv, "bdfioprvRS:V:", long_opts, &ind))
  124.      != EOF)
  125.     {
  126.       if (c == 0 && long_opts[ind].flag == NULL)
  127.     c = long_opts[ind].val;
  128.       switch (c)
  129.     {
  130.     case 0:
  131.       break;
  132.  
  133.     case 'b':
  134.       make_backups = 1;
  135.       break;
  136.  
  137.     case 'd':
  138.       flag_dereference = 0;
  139.       break;
  140.  
  141.     case 'f':
  142.       flag_force = 1;
  143.       break;
  144.  
  145.     case 'i':
  146.       flag_interactive = 1;
  147.       break;
  148.  
  149.     case 'o':
  150.       flag_one_file_system = 1;
  151.       break;
  152.  
  153.     case 'p':
  154.       flag_preserve = 1;
  155.       break;
  156.  
  157.     case 'r':
  158.     case 'R':
  159.       flag_recursive = 1;
  160.       break;
  161.  
  162.     case 'v':
  163.       flag_verbose = 1;
  164.       break;
  165.  
  166.     case 'S':
  167.       simple_backup_suffix = optarg;
  168.       break;
  169.  
  170.     case 'V':
  171.       version = optarg;
  172.       break;
  173.  
  174.     default:
  175.       usage ((char *) 0);
  176.     }
  177.     }
  178.  
  179.   if (make_backups)
  180.     backup_type = get_version (version);
  181.  
  182.   if (flag_interactive)
  183.     flag_force = 0;
  184.  
  185.   if (flag_preserve == 1)
  186.     umask_kill = 0777777;
  187.  
  188.   /* The key difference between -d (+no-dereference) and not is the version
  189.      of `stat' to call.  */
  190.  
  191.   if (flag_dereference)
  192.     xstat = stat;
  193.   else
  194.     xstat = lstat;
  195.  
  196.   stdin_not_tty = !isatty (0);
  197.   root = (geteuid () == 0);
  198.  
  199.   /* Allocate space for remembering copied and created files.  */
  200.  
  201.   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
  202.  
  203.   exit_status |= do_copy (argc, argv);
  204.  
  205.   exit (exit_status);
  206. }
  207.  
  208. /* Scan the arguments, and copy each by calling `copy'.
  209.    Return 0 if successful, 1 if any errors occur. */
  210.  
  211. int
  212. do_copy (argc, argv)
  213.      int argc;
  214.      char *argv[];
  215. {
  216.   char *target;
  217.   struct stat sb;
  218.   int new_dst = 0;
  219.   int ret = 0;
  220.  
  221.   if (optind >= argc)
  222.     usage ("missing file arguments");
  223.   if (optind >= argc - 1)
  224.     usage ("missing file argument");
  225.  
  226.   target = argv[argc - 1];
  227.  
  228.   strip_trailing_slashes (target);
  229.  
  230.   if (lstat (target, &sb))
  231.     {
  232.       if (errno != ENOENT)
  233.     {
  234.       error (0, errno, "%s", target);
  235.       return 1;
  236.     }
  237.       else
  238.     new_dst = 1;
  239.     }
  240.   else
  241.     {
  242.       struct stat sbx;
  243.  
  244.       /* If `target' is not a symlink to a nonexistent file, use
  245.      the results of stat instead of lstat, so we can copy files
  246.      into symlinks to directories. */
  247.       if (stat (target, &sbx) == 0)
  248.     sb = sbx;
  249.     }
  250.  
  251.   if (!new_dst && (sb.st_mode & S_IFMT) == S_IFDIR)
  252.     {
  253.       /* cp e_file_1...e_file_n e_dir
  254.      copy the files `e_file_1' through `e_file_n'
  255.      to the existing directory `e_dir'. */
  256.  
  257.       for (;;)
  258.     {
  259.       char *arg;
  260.       char *ap;
  261.       char *dst_path;
  262.  
  263.       arg = argv[optind];
  264.  
  265.       strip_trailing_slashes (arg);
  266.  
  267.       /* Append the last component of `arg' to `target'.  */
  268.  
  269.       ap = rindex (arg, '/');
  270.       if (ap == 0)
  271.         ap = arg;
  272.       else
  273.         ap++;
  274.       dst_path = xmalloc (strlen (target) + strlen (ap) + 2);
  275.       str_cpy (str_cpy (str_cpy (dst_path, target), "/"), ap);
  276.  
  277.       ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
  278.       forget_all ();
  279.  
  280.       ++optind;
  281.       if (optind == argc - 1)
  282.         break;
  283.     }
  284.       return ret;
  285.     }
  286.   else if (argc - optind == 2)
  287.     return copy (argv[optind], target, new_dst, 0, (struct dir_list *) 0);
  288.   else
  289.     usage ("when copying multiple files, last argument must be a directory");
  290. }
  291.  
  292. /* Copy the file `src_path' to the file `dst_path'.  The files may be of
  293.    any type.  If the file `dst_path' cannot exist because its parent
  294.    directory was just created, `new_dst' should be non-zero.  If
  295.    `dst_path' might already exist, `new_dst' should be zero.
  296.    `device' is the device number of the parent directory, or 0 if
  297.    this file has no known parent.  `ancestors' points to a linked, null
  298.    terminated list of parent directories of `src_path'.
  299.    Return 0 if successful, 1 if an error occurs. */
  300.  
  301. int
  302. copy (src_path, dst_path, new_dst, device, ancestors)
  303.      char *src_path;
  304.      char *dst_path;
  305.      int new_dst;
  306.      dev_t device;
  307.      struct dir_list *ancestors;
  308. {
  309.   struct stat src_sb;
  310.   struct stat dst_sb;
  311.   int mode;
  312.   int type;
  313.   char *earlier_file;
  314.   int may_overwrite;
  315.   char *dst_backup = NULL;
  316.  
  317.   if ((*xstat) (src_path, &src_sb))
  318.     {
  319.       error (0, errno, "%s", src_path);
  320.       return 1;
  321.     }
  322.  
  323.   /* Are we crossing a file system boundary?  */
  324.   if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
  325.     return 0;
  326.  
  327.   /* We wouldn't insert a node unless nlink > 1, except that we need to
  328.      find created files so as to not copy infinitely if a directory is
  329.      copied into itself.  */
  330.  
  331.   earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
  332.  
  333.   /* Have we encountered a file just created?  */
  334.  
  335.   if (earlier_file == &new_file)
  336.     return 0;
  337.  
  338.   if (flag_verbose)
  339.     printf ("  %s -> %s\n", src_path, dst_path);
  340.  
  341.   /* Did we copy this inode somewhere else (in this command line argument)
  342.      and therefore this is a second hard link to the inode?  */
  343.  
  344.   if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
  345.     {
  346.       if (!new_dst)
  347.     {
  348.       if (backup_type != none)
  349.         {
  350.           dst_backup = find_backup_file_name (dst_path);
  351.           if (dst_backup == NULL)
  352.         error (1, 0, "virtual memory exhausted");
  353.           if (rename (dst_path, dst_backup))
  354.         {
  355.           if (errno != ENOENT)
  356.             {
  357.               error (0, errno, "cannot backup `%s'", dst_path);
  358.               free (dst_backup);
  359.               return 1;
  360.             }
  361.           else
  362.             {
  363.               free (dst_backup);
  364.               dst_backup = NULL;
  365.             }
  366.         }
  367.         }
  368.       else if (unlink (dst_path) && errno != ENOENT)
  369.         {
  370.           error (0, errno, "cannot remove old link `%s'", dst_path);
  371.           return 1;
  372.         }
  373.     }
  374.       if (link (earlier_file, dst_path))
  375.     {
  376.       error (0, errno, "cannot create link `%s'", dst_path);
  377.       goto un_backup;
  378.     }
  379.       if (dst_backup)
  380.     free (dst_backup);
  381.       return 0;
  382.     }
  383.  
  384.   mode = src_sb.st_mode;
  385.   type = src_sb.st_mode & S_IFMT;
  386.  
  387.   if (type == S_IFDIR && !flag_recursive)
  388.     {
  389.       error (0, 0, "%s: omitting directory", src_path);
  390.       return 1;
  391.     }
  392.  
  393.   if (!new_dst)
  394.     {
  395.       if ((*xstat) (dst_path, &dst_sb))
  396.     {
  397.       if (errno != ENOENT)
  398.         {
  399.           error (0, errno, "%s", dst_path);
  400.           return 1;
  401.         }
  402.       else
  403.         new_dst = 1;
  404.     }
  405.       else
  406.     {
  407.       /* The file exists already.  */
  408.  
  409.       if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
  410.         {
  411.           error (0, 0, "`%s' and `%s' are the same file (omitted)",
  412.              src_path, dst_path);
  413.           return 1;
  414.         }
  415.  
  416.       if ((dst_sb.st_mode & S_IFMT) == S_IFDIR && type != S_IFDIR)
  417.         {
  418.           error (0, 0, "%s: cannot overwrite directory with non-directory",
  419.              dst_path);
  420.           return 1;
  421.         }
  422.  
  423.       /* Treat the file as nonwritable if it lacks write permission bits,
  424.          even if we are root.  */
  425. #ifdef S_IFLNK
  426.       if (type == S_IFLNK)
  427.         may_overwrite = 1;
  428.       else
  429. #endif
  430.         may_overwrite =
  431.           eaccess_stat (&dst_sb,
  432.                 type == S_IFDIR ? (W_OK | X_OK) : W_OK) == 0
  433.                   && (dst_sb.st_mode & 0222)
  434.                 && (type != S_IFDIR
  435.                     || (dst_sb.st_mode & 0111));
  436.  
  437.       if (flag_interactive)
  438.         {
  439.           fprintf (stderr, "%s: replace `%s'? ", program_name, dst_path);
  440.           if (!yesno ())
  441.         return 0;
  442.         }
  443.       else if (!flag_force && !may_overwrite)
  444.         {
  445.           if (stdin_not_tty)
  446.         {
  447.           error (0, 0, "%s: no write permission", dst_path);
  448.           return 1;
  449.         }
  450.           fprintf (stderr, "%s: override mode %04o for `%s'? ",
  451.                program_name, dst_sb.st_mode & 0777, dst_path);
  452.           if (!yesno ())
  453.         return 0;
  454.         }
  455.  
  456.       if (backup_type != none)
  457.         {
  458.           dst_backup = find_backup_file_name (dst_path);
  459.           if (dst_backup == NULL)
  460.         error (1, 0, "virtual memory exhausted");
  461.           if (rename (dst_path, dst_backup))
  462.         {
  463.           if (errno != ENOENT)
  464.             {
  465.               error (0, errno, "cannot backup `%s'", dst_path);
  466.               free (dst_backup);
  467.               return 1;
  468.             }
  469.           else
  470.             {
  471.               free (dst_backup);
  472.               dst_backup = NULL;
  473.             }
  474.         }
  475.           new_dst = 1;
  476.         }
  477.       else if (!may_overwrite)
  478.         {
  479.           if (type == S_IFDIR)
  480.         {
  481.           /* Temporarily change mode to allow overwriting. */
  482.           if (chmod (dst_path, dst_sb.st_mode | S_IEXEC | S_IWRITE))
  483.             {
  484.               error (0, errno, "%s", dst_path);
  485.               return 1;
  486.             }
  487.         }
  488.           else
  489.         {
  490.           if (unlink (dst_path) && errno != ENOENT)
  491.             {
  492.               error (0, errno, "cannot remove old link to `%s'",
  493.                  dst_path);
  494.               return 1;
  495.             }
  496.           new_dst = 1;
  497.         }
  498.         }
  499.     }
  500.     }
  501.  
  502.   if (!flag_recursive)
  503.     {
  504.       if (copy_reg (src_path, dst_path))
  505.     goto un_backup;
  506.     }
  507.   else
  508.     switch (type)
  509.       {
  510. #ifdef S_IFIFO
  511.       case S_IFIFO:
  512.     /* If a fifo already exists, we cannot do a better one.  */
  513.     if (new_dst)
  514.       {
  515.         if (mkfifo (dst_path, mode & umask_kill))
  516.           {
  517.         error (0, errno, "cannot make fifo `%s'", dst_path);
  518.         goto un_backup;
  519.           }
  520.       }
  521.     break;
  522. #endif
  523.  
  524.       case S_IFBLK:
  525.       case S_IFCHR:
  526. #ifdef S_IFSOCK
  527.       case S_IFSOCK:
  528. #endif
  529.     if (!root)
  530.       {
  531.         error (0, 0, "%s: omitting special file", src_path);
  532.         goto un_backup;
  533.       }
  534.     if (!new_dst && unlink (dst_path) && errno != ENOENT)
  535.       {
  536.         error (0, errno, "cannot remove old link to `%s'", dst_path);
  537.         return 1;
  538.       }
  539.     
  540.     if (mknod (dst_path, mode & umask_kill, src_sb.st_rdev))
  541.       {
  542.         error (0, errno, "cannot create special file `%s'", dst_path);
  543.         goto un_backup;
  544.       }
  545.     break;
  546.  
  547.       case S_IFDIR:
  548.     {
  549.       struct dir_list *dir;
  550.  
  551.       /* If this directory has been copied before during the
  552.          recursion, there's a symbolic link to an ancestor
  553.          directory of the symbolic link.  It's impossible to
  554.          continue to copy this, unless we've got an infinite disk.  */
  555.  
  556.       if (is_ancestor (&src_sb, ancestors))
  557.         {
  558.           error (0, 0, "%s: omitting cyclic symbolic link", src_path);
  559.           goto un_backup;
  560.         }
  561.  
  562.       /* Insert the current directory in the list of parents.  */
  563.  
  564.       dir = (struct dir_list *) alloca (sizeof (struct dir_list));
  565.       dir->parent = ancestors;
  566.       dir->ino = src_sb.st_ino;
  567.       dir->dev = src_sb.st_dev;
  568.  
  569.       /* Create the directory.  If a directory already exists, we
  570.          cannot create a better one.  */
  571.  
  572.       if (new_dst)
  573.         {
  574.           /* Create the new directory writable and searchable, so
  575.          we can create new entries in it.  */
  576.  
  577.           if (mkdir (dst_path, 0700))
  578.         {
  579.           error (0, errno, "cannot create directory `%s'", dst_path);
  580.           goto un_backup;
  581.         }
  582.  
  583.           /* Insert the created directory's inode and device
  584.          numbers into the search structure, so that we can
  585.          avoid copying it again.  */
  586.           
  587.           if (remember_created (dst_path))
  588.         goto un_backup;
  589.         }
  590.  
  591.       /* Now, copy the contents of the directory.  */
  592.  
  593.       if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
  594.         goto err_return;
  595.     }
  596.     break;
  597.  
  598.       case S_IFREG:
  599.     if (copy_reg (src_path, dst_path))
  600.       goto un_backup;
  601.     break;
  602.  
  603. #ifdef S_IFLNK
  604.       case S_IFLNK:
  605.     {
  606.       char *link_val = (char *) alloca (src_sb.st_size + 1);
  607.  
  608.       if (readlink (src_path, link_val, src_sb.st_size) < 0)
  609.         {
  610.           error (0, errno, "cannot read symbolic link `%s'", src_path);
  611.           goto un_backup;
  612.         }
  613.       link_val[src_sb.st_size] = '\0';
  614.  
  615.       if (!new_dst && unlink (dst_path) && errno != ENOENT)
  616.         {
  617.           error (0, errno, "cannot remove old link to `%s'", dst_path);
  618.           return 1;
  619.         }
  620.  
  621.       if (symlink (link_val, dst_path))
  622.         {
  623.           error (0, errno, "cannot create symbolic link `%s'", dst_path);
  624.           goto un_backup;
  625.         }
  626.     }
  627.     return 0;
  628. #endif
  629.  
  630.       default:
  631.     error (0, 0, "%s: unknown file type (omitted)", src_path);
  632.     goto un_backup;
  633.       }
  634.  
  635.   if ((flag_preserve || new_dst) && (type == S_IFREG || type == S_IFDIR))
  636.     {
  637.       if (chmod (dst_path, mode & umask_kill))
  638.     {
  639.       error (0, errno, "%s", dst_path);
  640.       goto err_return;
  641.     }
  642.     }
  643.   else if (type == S_IFDIR && !new_dst && !may_overwrite)
  644.     {
  645.       /* Reset the temporarily changed mode.  */
  646.       if (chmod (dst_path, dst_sb.st_mode))
  647.     {
  648.       error (0, errno, "%s", dst_path);
  649.       goto err_return;
  650.     }
  651.     }
  652.  
  653.   /* Adjust the times (and if possible, ownership) for the copy. */
  654.  
  655.   if (flag_preserve)
  656.     {
  657.       struct utimbuf tv;
  658.  
  659.       tv.actime = src_sb.st_atime;
  660.       tv.modtime = src_sb.st_mtime;
  661.  
  662.       if (utime (dst_path, &tv))
  663.     {
  664.       error (0, errno, "%s", dst_path);
  665.       goto err_return;
  666.     }
  667.  
  668.       if (chown (dst_path, src_sb.st_uid, src_sb.st_gid) && errno != EPERM)
  669.     {
  670.       error (0, errno, "%s", dst_path);
  671.       goto err_return;
  672.     }
  673.     }
  674.  
  675.   if (dst_backup)
  676.     free (dst_backup);
  677.   return 0;
  678.  
  679.  err_return:
  680.   if (dst_backup)
  681.     free (dst_backup);
  682.   return 1;
  683.  
  684.  un_backup:
  685.   if (dst_backup)
  686.     {
  687.       if (rename (dst_backup, dst_path))
  688.     error (0, errno, "cannot un-backup `%s'", dst_path);
  689.       free (dst_backup);
  690.     }
  691.   return 1;
  692. }
  693.  
  694. /* Read the contents of the directory `src_path_in', and recursively
  695.    copy the contents to `dst_path_in'.  `new_dst' is non-zero if
  696.    `dst_path_in' is a directory that was created previously in the
  697.    recursion.  Return 0 if successful, -1 if an error occurs. */
  698.  
  699. int
  700. copy_dir (src_path_in, dst_path_in, new_dst, src_sb, ancestors)
  701.      char *src_path_in;
  702.      char *dst_path_in;
  703.      int new_dst;
  704.      struct stat *src_sb;
  705.      struct dir_list *ancestors;
  706. {
  707.   char *name_space;
  708.   char *namep;
  709.   char *src_path;
  710.   char *dst_path;
  711.   int ret = 0;
  712.  
  713.   errno = 0;
  714.   name_space = savedir (src_path_in, src_sb->st_size);
  715.   if (name_space == 0)
  716.     {
  717.       if (errno)
  718.     {
  719.       error (0, errno, "%s", src_path_in);
  720.       return -1;
  721.     }
  722.       else
  723.     error (1, 0, "virtual memory exhausted");
  724.     }
  725.  
  726.   namep = name_space;
  727.   while (*namep != '\0')
  728.     {
  729.       int fn_length = strlen (namep) + 1;
  730.  
  731.       dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
  732.       src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
  733.  
  734.       str_cpy (str_cpy (str_cpy (src_path, src_path_in), "/"), namep);
  735.       str_cpy (str_cpy (str_cpy (dst_path, dst_path_in), "/"), namep);
  736.  
  737.       ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
  738.  
  739.       /* Free the memory for `src_path'.  The memory for `dst_path'
  740.      cannot be deallocated, since it is used to create multiple
  741.      hard links.  (Of course it is possible to optimize memory
  742.      allocation, as most files have only one link.)  */
  743.  
  744.       free (src_path);
  745.  
  746.       namep += fn_length;
  747.     }
  748.   free (name_space);
  749.   return -ret;
  750. }
  751.  
  752. /* Copy a regular file from `src_path' to `dst_path'.  Large blocks of zeroes,
  753.    as well as holes in the source file, are made into holes in the
  754.    target file.  (Holes are read as zero by the `read' system call.)
  755.    Return 0 if successful, -1 if an error occurred. */
  756.  
  757. int
  758. copy_reg (src_path, dst_path)
  759.      char *src_path;
  760.      char *dst_path;
  761. {
  762.   char *buf;
  763.   int buf_size;
  764.   int target_desc;
  765.   int source_desc;
  766.   int n_read;
  767.   int n_written;
  768.   struct stat sb;
  769.   int return_val = 0;
  770.   long n_read_total = 0;
  771.   char *cp;
  772.   int *ip;
  773.   int last_write_made_hole = 0;
  774.  
  775.   source_desc = open (src_path, O_RDONLY);
  776.   if (source_desc < 0)
  777.     {
  778.       error (0, errno, "%s", src_path);
  779.       return -1;
  780.     }
  781.  
  782.   /* Create the new regular file with small permissions initially,
  783.      not to create a security hole.  */
  784.  
  785.   target_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  786.   if (target_desc < 0)
  787.     {
  788.       error (0, errno, "cannot create regular file `%s'", dst_path);
  789.       return_val = -1;
  790.       goto ret2;
  791.     }
  792.  
  793.   /* Find out the appropriate buffer length.  */
  794.  
  795.   if (fstat (target_desc, &sb))
  796.     {
  797.       error (0, errno, "%s", dst_path);
  798.       return_val = -1;
  799.       goto ret;
  800.     }
  801.  
  802.   buf_size = ST_BLKSIZE (sb);
  803.  
  804.   /* Make a buffer with space for a sentinel at the end.  */
  805.  
  806.   buf = (char *) alloca (buf_size + sizeof (int));
  807.  
  808.   for (;;)
  809.     {
  810.       n_read = read (source_desc, buf, buf_size);
  811.       if (n_read < 0)
  812.     {
  813.       error (0, errno, "%s", src_path);
  814.       return_val = -1;
  815.       goto ret;
  816.     }
  817.       if (n_read == 0)
  818.     break;
  819.  
  820.       n_read_total += n_read;
  821.  
  822.       buf[n_read] = 1;        /* Sentinel to stop loop.  */
  823.  
  824.       /* Find first non-zero *word*, or the word with the sentinel.  */
  825.  
  826.       ip = (int *) buf;
  827.       while (*ip++ == 0)
  828.     ;
  829.  
  830.       /* Find the first non-zero *byte*, or the sentinel.  */
  831.  
  832.       cp = (char *) (ip - 1);
  833.       while (*cp++ == 0)
  834.     ;
  835.  
  836.       /* If we found the sentinel, the whole input block was zero,
  837.      and we can make a hole.  */
  838.  
  839.       if (cp > buf + n_read)
  840.     {
  841.       /* Make a hole.  */
  842.       if (lseek (target_desc, (off_t) n_read, L_INCR) < 0L)
  843.         {
  844.           error (0, errno, "%s", dst_path);
  845.           return_val = -1;
  846.           goto ret;
  847.         }
  848.       last_write_made_hole = 1;
  849.     }
  850.       else
  851.     {
  852.       n_written = write (target_desc, buf, n_read);
  853.       if (n_written < n_read)
  854.         {
  855.           error (0, errno, "%s", dst_path);
  856.           return_val = -1;
  857.           goto ret;
  858.         }
  859.       last_write_made_hole = 0;
  860.     }
  861.     }
  862.  
  863.   /* If the file ends with a `hole', something needs to be written at
  864.      the end.  Otherwise the kernel would truncate the file at the end
  865.      of the last write operation.  */
  866.  
  867.   if (last_write_made_hole)
  868.     {
  869. #ifndef FTRUNCATE_MISSING
  870.       /* Write a null character and truncate it again.  */
  871.       if (write (target_desc, "", 1) != 1
  872.       || ftruncate (target_desc, n_read_total) < 0)
  873. #else
  874.       /* Seek backwards one character and write a null.  */
  875.       if (lseek (target_desc, (off_t) -1, L_INCR) < 0L
  876.       || write (target_desc, "", 1) != 1)
  877. #endif
  878.     {
  879.       error (0, errno, "%s", dst_path);
  880.       return_val = -1;
  881.     }
  882.     }
  883.  
  884. ret:
  885.   close (target_desc);
  886. ret2:
  887.   close (source_desc);
  888.  
  889.   return return_val;
  890. }
  891.